<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class mpostcategory extends MY_Model {

    var $theme_data = array(
        'layout_main' => 'layout',
        'left' => 'include/leftcp',
    );
    public $mytable = "post_category";
    public $primaryKey = "pcat_id";
    public $resCode = "POST_CATEGORY";

    function __construct() {
        parent::__construct();
    }

    function field() {
        $fieldData = array();
        $fieldData['pos_id'] = 0;
        $fieldData['cat_id'] = 0;
        $fieldData['pcat_time'] = 0;
        $fieldData['pcat_user'] = 0;
        return $fieldData;
    }

    /**
     * Bai viet thuc hien them gan category 
     * can disable debug mod;
     * @param int $post_id
     * @param array $categories of id
     */
    public function post_category_it($post_id, $categories) {
        $db_debug = $this->db->db_debug;
        $this->db->db_debug = false;
        if (is_array($categories) && !empty($categories)) {

            //delete removed categories;
            $this->db->where('pos_id', $post_id);
            $this->db->where_not_in('cat_id', $categories);
            $this->db->delete($this->mytable);
            $data_cat_insert = array();
            foreach ($categories as $tag) {
                $data_cat_insert = array(
                    'pos_id' => $post_id,
                    'cat_id' => $tag,
                    'pcat_time' => time(),
                    //'pcat_user' => $this->madmin->adm_id
                );
                $this->db->insert($this->mytable, $data_cat_insert);
            }
        } else {
            $this->delete($post_id, 'pos_id');
        }
        // $this->db->db_debug = $db_debug;
    }    

    public function get_category_post($post_id) {
        $post_id = (int) $post_id;
        $result = $this->gets(array('pos_id' => $post_id));
        $ids = array();
        if ($result)
            foreach ($result as $item) {
                $ids[] = $item->cat_id;
            }
        return $ids;
    }

    public function get_post_category($catids) {
        $this->db->select('pos_id');
        $this->db->where_in('cat_id', $catids);
        $this->db->group_by('post_category.pos_id');
        $result = $this->db->get($this->mytable)->result();
        $ids = array();
        if ($result)
            foreach ($result as $item) {
                $ids[] = $item->pos_id;
            }
        return $ids;
    }
}

?>